﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;

namespace pngpacker
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void move(int from, int to)
		{
			object item = listBox1.Items[from];
			listBox1.Items.RemoveAt(from);
			listBox1.Items.Insert(to, item);
			listBox1.SelectedIndex = to;
		}

		private void listBox1_DoubleClick(object sender, EventArgs e)
		{
			if (listBox1.SelectedIndex < 0)
				return;
			System.Diagnostics.Process.Start((string)listBox1.SelectedItem);
		}

		private void listBox1_DragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				e.Effect = DragDropEffects.Link;
			}
			else
			{
				e.Effect = DragDropEffects.None;
			}
		}

		private void button4_Click(object sender, EventArgs e)
		{
			if (listBox1.Items.Count == 0)
			{
				return;
			}
			Form2 export = new Form2();
			LinkedList<string> fileList = new LinkedList<string>();
			foreach (object item in listBox1.Items)
			{
				string s = item as string;
				if (s != null)
					fileList.AddLast(s);
			}
			export.Files = fileList;
			export.ShowDialog();
		}

		private void listBox1_DragDrop(object sender, DragEventArgs e)
		{
			string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];
			if (files == null)
				return;
			foreach (string file in files)
			{
				bool valid = file.EndsWith(".png", StringComparison.OrdinalIgnoreCase);
				if (!valid)
					valid = file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase);
				if (!valid)
					valid = file.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase);
				if (valid)
					listBox1.Items.Add(file);
			}
		}

		private void button1_Click(object sender, EventArgs e)
		{
			int index = listBox1.SelectedIndex;
			if (index < 1)
			{
				return;
			}
			move(index, index - 1);
		}

		private void button2_Click(object sender, EventArgs e)
		{
			int index = listBox1.SelectedIndex;
			if (index < 0 || index >= listBox1.Items.Count - 1)
			{
				return;
			}
			move(index, index + 1);
		}

		private void button3_Click(object sender, EventArgs e)
		{
			if (listBox1.SelectedIndex < 0)
			{
				return;
			}
			int index = listBox1.SelectedIndex;
			listBox1.Items.RemoveAt(index);
			int count = listBox1.Items.Count;
			if (index < count)
			{
				listBox1.SelectedIndex = index;
			}
			else if (count > 0)
			{
				listBox1.SelectedIndex = count - 1;
			}
		}

		private void checkBox1_CheckedChanged(object sender, EventArgs e)
		{
			listBox1.Sorted = checkBox1.Checked;
		}

		private void listBox1_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Delete)
			{
				button3_Click(sender, null);
				e.Handled = true;
			}
		}
	}
}
